<?php
class organization_operation{
    // 应用实例对象
    static private $app='organization';

    // 模型实例
    static private $model;
    
    // 外部可调用的地区数组
    public $regions;

    // 构造方法
    public function __construct($app){
        if(!isset(self::$model)){
            self::$model = app::get(self::$app)->model('organization');
        }
    }

    /**
     * 得到组织信息 
     */
    public function getGropById($orgId='',$orgType=''){
        if ($orgId){
            $base_filter = array('parent_id' => $orgId,'del_mark' => 0);
        }else{
            $base_filter = array('org_level_num' => '1','del_mark' => 0);
        }

        if($orgType){
            $filter = array_merge($base_filter,array('org_type'=>$orgType));
            $aTemp = self::$model->getList('org_id,org_no,org_type,org_name,status,org_level_num', $filter, 0, -1, 'org_id ASC');
        }else{
            //门店管理页面重新获取$base_filter 显示启用的组织层级和相应的所属门店
            if($orgId){
                $base_filter = "parent_id=".$orgId;
            }else{
                //页面首次加载 显示最高组织层级
                $base_filter = "org_level_num=1";
            }
            $base_filter = $base_filter." and del_mark=0";
            $aTemp = self::$model->db->select("select org_id,org_no,org_type,org_name,status,org_level_num from ".DB_PREFIX."organization_organization where ".$base_filter." and (org_type=2 or (org_type=1 and status=1)) order by org_id ASC");
        }
        
        if (is_array($aTemp)&&count($aTemp) > 0){
            foreach($aTemp as $key => $val){
                $aTemp[$key]['status']=intval($val['status']);
                $aTemp[$key]['child_count'] = $this->getChildCount($val['org_id'],$orgType);
                $aTemp[$key]['step'] = intval($val['org_level_num'])-1;
            }
        }
        return $aTemp;
    }
    
    /**
     * 获取指定的下级组织数量
     */
    private function getChildCount($org_id, $org_type=''){
        if($org_type){
            $filter = array('parent_id' => $org_id,'del_mark' => 0,'org_type'=>$org_type);
            $cnt = self::$model->count($filter);
        }else{
            //门店管理页面显示启用的组织层级和相应的所属门店
            $cnt = self::$model->db->count("select count(*) from ".DB_PREFIX."organization_organization where parent_id=".intval($org_id)." and del_mark=0 and (org_type=2 or (org_type=1 and status=1))");
        }
        return $cnt;
    }

}
